package com.xyy.jd_clund.utils;

import cn.hutool.core.date.DateUtil;
import com.kingdee.service.ApiException;
import com.kingdee.service.data.api.AppTokenApi;
import com.kingdee.service.data.api.AuthorizeApi;
import com.kingdee.service.data.entity.AsterAppTokenRes;
import com.kingdee.service.data.entity.AsterAuthorizeRes;
import com.kingdee.service.unit.SHAUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * @Author itmei
 * @Date 2023/7/16 13:20
 * @description: 缓存token
 * @Title: TokenCache
 * @Package com.xyy.jd_clund.utils
 */
@Slf4j
public class TokenCache {

    private static String token;
    private static Long expirationTime;

    public static synchronized String getToken() {
        // 检查Token是否存在且未过期
        long time = DateUtils.getDayEnd().getTime();
        if (token != null && expirationTime < time) {
            return token; // 返回现有的Token
        }
        String newToken = null;
        try {
            // 如果Token不存在或已过期，则重新获取Token
            AuthorizeApi authorizeApi = new AuthorizeApi();
            List<AsterAuthorizeRes> asterAuthorizeResList = authorizeApi.asterAuthorize("155112317951021056");
            AsterAuthorizeRes asterAuthorizeRes = asterAuthorizeResList.get(0);
            String appKey = asterAuthorizeRes.getAppKey();
            String appSecret = asterAuthorizeRes.getAppSecret();
            AppTokenApi appTokenApi = new AppTokenApi();
            String appSignature = SHAUtil.SHA256HMAC(appKey, appSecret);
            appSignature = Base64.getEncoder().encodeToString(appSignature.getBytes());
            AsterAppTokenRes asterAppTokenRes = appTokenApi.asterAppToken(appKey, appSignature, null);
            newToken = asterAppTokenRes.getAppToken();
            // 假设获取到的新Token为newToken
            token = newToken;
            expirationTime = new Date().getTime(); // 设置Token有效期为一天
            log.info("Token过期重新获取:{} ", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }
        return newToken; // 返回新获取的Token
    }
}
